<template>
  <div>
    <common-head :title="$route.name" />
    <div class="container">
      <van-address-list
        v-model="chosenAddressId"
        :list="list"
        @select="switchContact"
        default-tag-text="默认"
        @add="onAdd"
        @edit="onEdit"
      />
    </div>
  </div>
</template>

<script>
import CommonHead from '../../components/CommonHead.vue'
import { fetchAddress } from '_api'
import { getToken } from '_utils'

export default {
  data () {
    return {
      chosenAddressId: '', // 默认联系人id
      list: [
        // 联系人列表
      ]
    }
  },
  created () {
    this.fetchAddress()
  },
  beforeRouteEnter (to, from, next) {
    if (from.path === '/order') {
      // 从订单页进来的
      from = 'order'
    } else {
      from = '其他'
    }
    next()
  },
  methods: {
    switchContact (contact) {
      // 切换联系人
      /*
        判断 我是从订单页进来列表
            回到定义订单页 并传 选中的地址 id
        还是其他路由
            啥都不干
      */
      const path = localStorage.getItem('path')
      if (path === '/order') {
        this.$router.replace({
          path: '/order',
          query: {
            contactId: contact.id
          }
        })
      }
    },
    fetchAddress () {
      // 获取所有收货人
      fetchAddress({
        token: getToken()
      }).then((res) => {
        if (res.data.code === 0) {
          const contacts = res.data.data.result
          console.log(contacts)
          // 定义一个空数组 接收 映射好的 数据
          const list = []
          contacts.forEach((contact) => {
            // 定义空对象 将 接收 contact 映射好的对象
            const address = {}
            for (const key in contact) {
              if (key === 'linkMan') {
                address.name = contact[key]
              } else if (key === 'mobile') {
                address.tel = contact[key]
              } else {
                address[key] = contact[key]
              }
            }
            list.push(address)
          })
          this.list = list //  字段映射
          // chosenAddressId 等于默认联系人的id   判断是否有默认联系人 find findIndex
          const defaultMan = list.find((contact) => contact.isDefault)
          if (defaultMan) {
            this.chosenAddressId = defaultMan.id
          } else {
            this.chosenAddressId = list[0].id
          }
        }
      })
    },
    onAdd () {
      // 点击添加联系人
      this.$router.push('/addressAdd')
    },
    onEdit (contact) {
      // 点击修改联系人
      console.log(contact)
      this.$router.push({
        path: '/addressUpdate',
        query: {
          contactId: contact.id
        }
      })
    }
  },
  components: { CommonHead }
}
</script>

<style lang="scss" scoped>
.container {
  padding-top: 46px;
}
</style>
